package com.jic.order.impl;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.order.entity.OrderDeliveryRelease;
import com.jic.order.entity.OrderDeliveryReleaseRelation;
import com.jic.order.entity.OrderManualDelivery;
import com.jic.order.manage.request.OrderDeliveryReleaseRelationRequest;
import com.jic.order.manage.request.OrderManualDeliveryRequest;
import com.jic.order.manage.response.OrderDeliveryReleaseRelationResponse;
import com.jic.order.mapper.OrderDeliveryReleaseMapper;
import com.jic.order.mapper.OrderDeliveryReleaseRelationMapper;
import com.jic.order.mapper.OrderManualDeliveryMapper;
import com.jic.order.service.OrderDeliveryReleaseRelationService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.jic.order.service.OrderManualDeliveryService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 交货单发布管理交易记录
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-05-29 04:59:34
 */
@Service
@Slf4j
public class OrderDeliveryReleaseRelationServiceImpl implements OrderDeliveryReleaseRelationService {

    @Autowired
    private OrderDeliveryReleaseRelationMapper orderDeliveryReleaseRelationMapper;

    @Autowired
    RedisClientTemplate redisClientTemplate;

    @Autowired
    OrderDeliveryReleaseMapper orderDeliveryReleaseMapper;

    @Autowired
    ProductListApi productListApi;

    @Autowired
    OrderManualDeliveryMapper orderManualDeliveryMapper;


    @Override
    public RestResult insert(OrderDeliveryReleaseRelationRequest orderDeliveryReleaseRelationRequest) {
        try {
            if (CollectionUtils.isEmpty(orderDeliveryReleaseRelationRequest.getOrderDeliveryReleaseRelationRequestList())) {
                return RestResult.error("9999", "购买数据不能为空!");
            }
            String userStr = redisClientTemplate.get(orderDeliveryReleaseRelationRequest.getToken());
            Map sysUser = JSONArray.parseObject(userStr, Map.class);
            orderDeliveryReleaseRelationRequest.getOrderDeliveryReleaseRelationRequestList().forEach(item -> {
                OrderDeliveryReleaseRelation orderDeliveryReleaseRelation = new OrderDeliveryReleaseRelation();
                BeanUtils.copyProperties(item, orderDeliveryReleaseRelation);
                orderDeliveryReleaseRelation.setBuyId(Long.valueOf(sysUser.get("merchantId").toString()));
                orderDeliveryReleaseRelationMapper.insert(orderDeliveryReleaseRelation);
            });
        } catch (Exception e) {
            log.error("OrderDeliveryReleaseRelationService.insert ========>", e);
            return RestResult.error("9999", "新增转交货单执行失败");
        }
        return RestResult.success("新增转交货单执行成功");
    }

    @Override
    public long delete(Long id) {
        return orderDeliveryReleaseRelationMapper.delete(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult update(OrderDeliveryReleaseRelationRequest orderDeliveryReleaseRelationRequest) {
        try {
                OrderDeliveryReleaseRelation orderDeliveryReleaseRelation = new OrderDeliveryReleaseRelation();
                orderDeliveryReleaseRelation.setBuyId(orderDeliveryReleaseRelationRequest.getBuyId());
                orderDeliveryReleaseRelation.setOrderNo(orderDeliveryReleaseRelationRequest.getOrderNo());
                List<OrderDeliveryReleaseRelation> orderDeliveryReleaseRelationList = orderDeliveryReleaseRelationMapper.query(orderDeliveryReleaseRelation);
                //审核通过
                if (orderDeliveryReleaseRelationRequest.getStatus() == 2) {
                    if (CollectionUtils.isNotEmpty(orderDeliveryReleaseRelationList)) {
                        orderDeliveryReleaseRelationList.forEach(item -> {
                            orderDeliveryReleaseRelation.setId(item.getId());
                            orderDeliveryReleaseRelation.setStatus(orderDeliveryReleaseRelationRequest.getStatus());
                            orderDeliveryReleaseRelationMapper.update(orderDeliveryReleaseRelation);

                            OrderDeliveryRelease orderDeliveryRelease = new OrderDeliveryRelease();
                            orderDeliveryRelease.setId(item.getOrderDeliveryReleaseId());
                            orderDeliveryRelease.setStatus(2);
                            orderDeliveryReleaseMapper.update(orderDeliveryRelease);

                            OrderManualDelivery orderManualDelivery = new OrderManualDelivery();
                            orderManualDelivery.setOrderStatus(2);
                            orderManualDelivery.setOrderNo(item.getOrderNo());
                            orderManualDelivery.setProductId(item.getProductId());
                            orderManualDelivery.setProductPrice(item.getBuyPrice());
                            orderManualDelivery.setProductNum(item.getProductNum());
                            orderManualDelivery.setTransferOutMerchantId(item.getSellId());
                            orderManualDelivery.setTransferToMerchantId(item.getBuyId());
                            orderManualDeliveryMapper.insert(orderManualDelivery);
                        });
                    }
                } else {
                    if (CollectionUtils.isNotEmpty(orderDeliveryReleaseRelationList)) {
                        orderDeliveryReleaseRelationList.forEach(item -> {
                            orderDeliveryReleaseRelation.setId(item.getId());
                            orderDeliveryReleaseRelation.setStatus(orderDeliveryReleaseRelationRequest.getStatus());
                            orderDeliveryReleaseRelationMapper.update(orderDeliveryReleaseRelation);

                            OrderDeliveryRelease orderDeliveryRelease = new OrderDeliveryRelease();
                            orderDeliveryRelease.setId(item.getOrderDeliveryReleaseId());
                            orderDeliveryRelease.setStatus(2);
                            orderDeliveryReleaseMapper.update(orderDeliveryRelease);

                        });
                    }
                }
                return RestResult.success("修改转交货单执行成功");


        } catch (Exception e) {
            log.error("OrderDeliveryReleaseRelationService.update ========>", e);
            return RestResult.error("9999", "修改转交货单执行失败");
        }

    }

    @Override
    public OrderDeliveryReleaseRelation queryByPrimaryKey(Long id) {
        return orderDeliveryReleaseRelationMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<OrderDeliveryReleaseRelation> query(OrderDeliveryReleaseRelation orderDeliveryReleaseRelation) {
        return orderDeliveryReleaseRelationMapper.query(orderDeliveryReleaseRelation);
    }

    @Override
    public RestResult<PageResult<OrderDeliveryReleaseRelationResponse>> queryPage(OrderDeliveryReleaseRelation orderDeliveryReleaseRelation, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();

        List<OrderDeliveryReleaseRelationResponse> list = orderDeliveryReleaseRelationMapper.queryPage(startIndex, pageQuery.getLimit(), orderDeliveryReleaseRelation)
                .stream().map(item -> {
                    OrderDeliveryReleaseRelationResponse response = new OrderDeliveryReleaseRelationResponse();
                    BeanUtils.copyProperties(item, response);
                    if (item.getProductId() != null) {
                        RestResult<ProductAfterInfoByIdResponse> responseRestResult = productListApi.queryProductInfoById(item.getProductId());
                        if (responseRestResult.getData() != null) {
                            response.setGoodsName(responseRestResult.getData().getChineseName());
                            response.setPictureUrl(responseRestResult.getData().getPictureUrl());
                        }
                    }
                    return response;
                }).collect(Collectors.toList());

        long count = orderDeliveryReleaseRelationMapper.queryPageCount(orderDeliveryReleaseRelation);

        PageResult<OrderDeliveryReleaseRelationResponse> pageResult = new PageResult();
        pageResult.setTotal(count);
        pageResult.setRows(list);

        return RestResult.success(pageResult);
    }
}